<?php


namespace App\Api\Fcjd;
use PhalApi\Api;
use PhalApi\Exception\BadRequestException;

/**
 * 非常检单-金币展示
 *
 * @author: dogstar <chanzonghuang@gmail.com> 2014-10-04
 */
class PhoneAppInfo extends Api
{

    public function getRules()
    {
        return array(
            'GetAppCoinInfo' => array(
                'oaid' => array('name' => 'oaid', 'require' => true, 'min' => 1, 'max' => 50, 'desc' => 'oaid')
            ),
            'GetAppCoinSummary' => array(
                'username' => array('name' => 'username', 'require' => true, 'min' => 1, 'max' => 50, 'desc' => 'username'),
                'size' => array('name' => 'size', 'require' => false, 'default' => 20, 'desc' => 'size'),
                'page' => array('name' => 'page', 'require' => false, 'default' => 1, 'desc' => 'page'),
                'appName' => array('name' => 'appName', 'require' => false, 'desc' => 'appName'),
            ),
            'GetAppCoinSummaryByAppName' => array(
                'username' => array('name' => 'username', 'require' => true, 'min' => 1, 'max' => 50, 'desc' => 'username'),
                'appName'=>array('name' => 'appName', 'require' => true, 'min' => 1, 'max' => 50, 'desc' => 'appName')
            ),
            'UpdateWithdrawType' => array(
                'mobile' => array('name' => 'mobile', 'require' => true),
                'app_name' => array('name' => 'app_name', 'require' => true),
                'config'=> array('name' => 'config', 'require' => true),
            ),
            'GetWithdrawType' => array(
                'mobile' => array('name' => 'mobile', 'require' => true)
            )
        );
    }


    /**
     * 获取APP收益信息
     * @desc APP收益信息
     * @return array data 获取APP收益信息
     * @exception 400 非法请求，参数传递错误
     */

    public function GetAppCoinInfo()
    {
        $oaid = $this->oaid;
        $phoneAppInfolist = \PhalApi\DI()->notorm->phone_app_info->select('apptodo,app_name')->where('oaid', $oaid)->fetchAll();
            // 检查 phoneAppInfolist 是否不为空
        if (!empty($phoneAppInfolist)) {
            $result = []; // 初始化结果数组
            foreach ($phoneAppInfolist as $appInfo) {
            // 解析 apptodo JSON
                $apptodoData = json_decode($appInfo['apptodo'], true); // 将 apptodo 转换为数组
        
                // 提取关键字
                $extractedData = [
                    'gold' => isset($apptodoData['gold']) ? $apptodoData['gold'] : null,
                    'money' => isset($apptodoData['money']) ? $apptodoData['money'] : null,
                    'packageName' => isset($apptodoData['packageName']) ? $apptodoData['packageName'] : null,
                ];
        
                // 将提取的数据与应用名称一起添加到结果数组
                $result[] = [
                'appName' => $appInfo['app_name'], // 获取应用名称
                'gold' => $extractedData['gold'], // 添加提取的 gold
                'money' => $extractedData['money'], // 添加提取的 money
                'packageName' => $extractedData['packageName'] // 添加提取的 packageName
                ]; 
            } 
        }
        return $result; 
    }

    /**
     * 获取APP收益汇总
     * @desc APP收益汇总
     * @return array data 获取APP收益汇总
     * @exception 400 非法请求，参数传递错误
     */
    public function GetAppCoinSummary(){
        $username = $this->username;
        $page = $this->page;
        $size = $this->size;
        $AppName = $this->appName;
        $where = array();

        if (!empty($username)) {
            $where['username'] = $username;  
        }
        if (!empty($AppName) && $AppName != '全部') {
            $where['app_name'] = $AppName; 
        }

        // return $where;

        $total = \PhalApi\DI()->notorm->phone_app_info->where($where)->count();
        $appInfolist = \PhalApi\DI()->notorm->phone_app_info->select('apptodo,name,app_name,mobile,date,yesterday_gold,before_yesterday_gold,mun,update_time,operate_date')
        ->where($where)
        ->limit(($page-1) * $size, $size)
        ->fetchAll();
        if (!empty($appInfolist)) {
            $result = []; // 初始化结果数组
            foreach ($appInfolist as $appInfo) {
                // 解析 apptodo JSON
                $apptodoData = json_decode($appInfo['apptodo'], true); // 将 apptodo 转换为数组
        
                // 提取关键字
                $extractedData = [
                    'gold' => isset($apptodoData['gold']) ? $apptodoData['gold'] : null,
                    'money' => isset($apptodoData['money']) ? $apptodoData['money'] : null,
                    'packageName' => isset($apptodoData['packageName']) ? $apptodoData['packageName'] : null,
                    'pay_done' => isset($apptodoData['pay_done']) ? $apptodoData['pay_done'] : null
                ];

                
                $yGoldBySelect =isset($appInfo['yesterday_gold']) ? $appInfo['yesterday_gold'] : null; 
                $beforeYesterdayGold =isset($appInfo['before_yesterday_gold']) ? $appInfo['before_yesterday_gold'] : null;
                $goldValue = $extractedData['gold'];
                
                $dateBySelect=date("Y-m-d", strtotime($appInfo['date']));
                $sysTime = time();
                $sysDate = date("Y-m-d", $sysTime);

                if($dateBySelect != $sysDate){
                   $beforeYesterdayGold = $yGoldBySelect;
                   $yesterdayGold = $goldValue;
                   $goldValue =0;
               }else{
                  $yesterdayGold =   $yGoldBySelect;
                  $beforeYesterdayGold= $beforeYesterdayGold;
               }
               
                // 将提取的数据与应用名称一起添加到结果数组
                $result[] = [
                    'appName' => $appInfo['app_name'], // 获取应用名称
                    'name' => $appInfo['name'], // 获取应用名称
                    'gold' => $this->FormatNumberWithPercent($goldValue), // 添加提取的 gold
                    'money' => $extractedData['money'], // 添加提取的 money
                    'packageName' => $extractedData['packageName'], // 添加提取的 packageName，
                    'mobile' => $appInfo['mobile'],
                    'yesterday_gold' =>$this->FormatNumberWithPercent($yesterdayGold),
                    'before_yesterday_gold' =>$this->FormatNumberWithPercent($beforeYesterdayGold),
                    'mun'=>$appInfo['mun'],
                    'pay_done'=> $extractedData['pay_done']
                ]; 
            } 
        }
        return array("data" => $result, "total" => $total); 
    }


    /**
     * 根据AppName获取APP收益汇总
     * @desc 根据AppName获取APP收益汇总
     * @return array data 根据AppName获取APP收益汇总
     * @exception 400 非法请求，参数传递错误
     */
    public function GetAppCoinSummaryByAppName(){
        $username = $this->username;
        $appNameInput= $this->appName;
        $appInfolist = \PhalApi\DI()->notorm->phone_app_info->select('apptodo,name,mobile,date,yesterday_gold,before_yesterday_gold,mun,update_time,operate_date')
        ->where(array('username' =>$username ,'app_name' => $appNameInput))
        ->fetchAll();
        if (!empty($appInfolist)) {
            $result = []; // 初始化结果数组
            foreach ($appInfolist as $appInfo) {
                // 解析 apptodo JSON
                $apptodoData = json_decode($appInfo['apptodo'], true); // 将 apptodo 转换为数组
        
                // 提取关键字
                $extractedData = [
                    'gold' => isset($apptodoData['gold']) ? $apptodoData['gold'] : null,
                    'money' => isset($apptodoData['money']) ? $apptodoData['money'] : null,
                    'packageName' => isset($apptodoData['packageName']) ? $apptodoData['packageName'] : null,
                    'pay_done' => isset($apptodoData['pay_done']) ? $apptodoData['pay_done'] : null
                ];
                 $yGoldBySelect =isset($appInfo['yesterday_gold']) ? $appInfo['yesterday_gold'] : null; 
                 $beforeYesterdayGold =isset($appInfo['before_yesterday_gold']) ? $appInfo['before_yesterday_gold'] : null;
                 $goldValue = $extractedData['gold'];
                 
                 $dateBySelect= date("Y-m-d", strtotime($appInfo['date']));
                 $sysTime = time();
                 $sysDate = date("Y-m-d", $sysTime);

                 if($dateBySelect != $sysDate){
                    $beforeYesterdayGold = $yGoldBySelect;
                    $yesterdayGold = $goldValue;
                    $goldValue =0;
                }else{
                    $yesterdayGold =   $yGoldBySelect;
                    $beforeYesterdayGold= $beforeYesterdayGold;
                }
                
        
                // 将提取的数据与应用名称一起添加到结果数组
                $result[] = [
                    'appName' => $appInfo['app_name'], // 获取应用名称
                    'name' => $appInfo['name'], // 获取应用名称
                    'gold' =>$this->FormatNumberWithPercent($goldValue), // 添加提取的 gold
                    'money' => $extractedData['money'], // 添加提取的 money
                    'packageName' => $extractedData['packageName'], // 添加提取的 packageName，
                    'mobile' => $appInfo['mobile'],
                    'yesterday_gold' =>$yesterdayGold,
                    'before_yesterday_gold' =>$this->FormatNumberWithPercent($beforeYesterdayGold),
                    'mun'=>$appInfo['mun'],
                    'pay_done'=> $extractedData['pay_done'],
                    'date' => $appInfo['date'],
                ];
                // 计算当天0点时间戳
                $todayStart = strtotime(date('Y-m-d 00:00:00'));
                foreach ($result as $key => $value) {
                    $dateTimestamp = strtotime($result[$key]['date']);
                    if( $dateTimestamp < $todayStart) {
                        $result[$key]['pay_done'] = " ";
                    }
                }
            } 
        }
        return $result; 
    }


    /**
     * 更新App提现设置
     * @desc  更新App提现设置
     * @return array data 更新App提现设置
     * @exception 400 非法请求，参数传递错误
     */
    public function UpdateWithdrawType(){
        $mobile = $this->mobile;
        $app_name = $this->app_name;
        $config = $this->config;

        $arr['config'] = $config;



        $paySetting =  \PhalApi\DI()->notorm->phone_app_info
                ->where(array(
                  'mobile'=>$mobile,
                    'app_name'=>$app_name))->fetchOne();

        if($paySetting){
            \PhalApi\DI()->notorm->phone_app_info
                ->where(array(
                    'mobile' => $mobile,
                    'app_name' => $app_name
                ))->update($arr);
            return array('msg' => '更新成功');
        }

        $device = \PhalApi\DI()->notorm->phone_list
            ->where('mobile', $mobile)
            ->fetchOne();

        $paySetting =  \PhalApi\DI()->notorm->phone_app_info
            ->insert(array(
                'username' => $device['username'],
                'app_name' => $app_name,
                'mobile' => $mobile,
                'config' => $config,
                'create_time' => date('Y-m-d H:i:s', time())
            ));
        return array('msg' => '更新成功');
       
    }

     /**
     * 获取App提现设置
     * @desc  获取App提现设置
     * @return array data 获取App提现设置
     * @exception 400 非法请求，参数传递错误
     */
    public function GetWithdrawType(){
        $mobile = $this->mobile;
        $phoneAppInfoList = \PhalApi\DI()
                                ->notorm->phone_app_info
                                ->select('config,app_name')
                                ->where('mobile', $mobile)
                                ->fetchAll();
        return $phoneAppInfoList;
    }

    /**
     * 更新数据
     * @desc 更新指定字段的数据
     * @param string $username 用户名
     * @param string $appname 应用名称
     * @param string $fieldName 应字段名
     * @param string $updateValue 更新字段值
     * @return array data 更新结果
     * @exception 400 非法请求，参数传递错误
     */
    private function UpdateAppInfoFeild($username, $appname, $fieldName,$updateValue) {
        // 检查参数是否有效
        if (empty($username) || empty($appname)) {
            \PhalApi\DI()->response->setMsg('参数错误');
            \PhalApi\DI()->response->setRet(400);
            return [];
        }

        // 更新数据库中的 yesterday_gold 字段
        $result = \PhalApi\DI()->notorm->phone_app_info
            ->where(array(
                'username' => $username,
                'app_name' => $appname
            ))
            ->update(array($fieldName => $updateValue));

        // 返回更新结果
        return $result;
    }


    private function FormatNumberWithPercent($value) {
        $hasPercent = false;
        $number = $value;

        // 检查是否包含百分号
        if (strpos($value, '%') !== false) {
            $hasPercent = true;
            $number = str_replace('%', '', $value);
        }

        // 检查是否为数字
        if (!is_numeric($number)) {
            if($hasPercent){
                return $number . '%';
            }else{
                return $value;
            }
        }

        if (floor($number) == $number) {
            if($hasPercent){
                return $number . '%';
            }else{
                return $number;
            }
        }
        
        if (strpos($number, '.') !== false) {
            $decimalCount = strlen(substr(strrchr($number, '.'), 1));
            if ($decimalCount > 2) {
                $number = number_format((float)$number, 2, '.', '');
            }
        }

        
        if (strpos($number, '.') !== false) {
            $number = number_format((float)$number, 2, '.', '');
        }

        if ($hasPercent) {
            $number .= '%';
        }

        return $number;
    }

}
